//
//  PSFileResponseHandler.m
//  PSExtensions
//
//  Created by PoiSon on 15/12/23.
//  Copyright © 2015年 yerl. All rights reserved.
//

#import "PSFileResponseHandler.h"
#import "PSHttpResponseHandler_Private.h"
#import "PSFoudation.h"

@implementation PSFileResponseHandler{
    PSFile *_cacheFile;
    BOOL _isFirstResume;
}
+ (instancetype)progress:(void (^)(long long, long long))progress success:(void (^)(NSString *, NSData *))success failure:(void (^)(NSError *))failure{
    PSFileResponseHandler *instance = [self new];
    instance.onProgress = progress;
    instance.onSuccess = success;
    instance.onFailure = failure;
    return instance;
}
- (void)processProgressWithWritten:(long long)bytesWritten total:(long long)totalBytesExpectedToWrite{
    [self ps_performBlockSync:^{
        doIf(self.onProgress, self.onProgress(bytesWritten, totalBytesExpectedToWrite));
    }];
}

- (void)processSuccessWithData:(NSData *)data{
    [self ps_performBlockSync:^{
        doIf(self.onSuccess, self.onSuccess(self.response.suggestedFilename, data));
    }];
}

- (void)processFailureWithData:(NSData *)data error:(NSError *)error{
    [self ps_performBlockSync:^{
        doIf(self.onFailure, self.onFailure(error));
    }];
}

#pragma mark - 处理断点下载相关的
- (NSString *)_cacheName{
    return [[_downloadRequest.URL absoluteString] ps_MD5Encoding];
}

- (void)setDownloadRequest:(NSMutableURLRequest *)downloadRequest{
    _downloadRequest = downloadRequest;
    _isFirstResume = YES;
    
    _cacheConfigFile = [[PSFile tmp] child:[[self _cacheName] stringByAppendingString:@".ps.cfg"]];
}

- (NSData *)cacheConfig{
    return [NSData dataWithContentsOfFile:self.cacheConfigFile.path];
}

/** 取消下载, 清除缓存 */
- (void)cancel{
    [self suspend];
    [self ps_performBlockSync:^{
        NSDictionary *cacheConfig = [NSDictionary dictionaryWithContentsOfFile:self.cacheConfigFile.path];
        [[[PSFile tmp] child:cacheConfig[@"NSURLSessionResumeInfoTempFileName"]] delete];
        [self.cacheConfigFile delete];
    } afterDelay:1];
}

/** 暂停下载, 将已下载的数据写入缓存 */
- (void)suspend{
    NSURLSessionDownloadTask *task = self._task;
    [task cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
        [resumeData writeToFile:self.cacheConfigFile.path atomically:YES];
    }];
}

/** 恢复下载 */
- (void)resume{
    self._task = [self._session downloadTaskWithResumeData:self.cacheConfig
                                                  progress:^(NSProgress * _Nonnull downloadProgress) {
                                                      [self _processProgress:downloadProgress];
                                                  }
                                               destination:nil
                                         completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
                                             if (error) {
                                                 [self _processFailureWithTask:self._task error:error];
                                             }else{
                                                 [self _processSuccessWithTask:self._task object:[NSData dataWithContentsOfURL:filePath]];
                                             }
                                             [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
                                         }];
    [self._task resume];
}
@end
